package kr.hkit.calendarproject11.Fragment;

import java.util.ArrayList;
import java.util.Calendar;

import kr.hkit.calendarproject11.Detail;
import kr.hkit.calendarproject11.R;
import kr.hkit.calendarproject11.DAO.DAO;
import kr.hkit.calendarproject11.DTO.DayInfo;
import kr.hkit.calendarproject11.DTO.MyItem;
import kr.hkit.calendarproject11.MyDBHelper.MyDBHelper;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MonthCalendar extends DialogFragment {
	final static String TAG = "DATE";
	MonthCalendarAdapter mCalendarAdapter;
	ArrayList<DayInfo> mDayList;
	ArrayList<MyItem> arList;
	int SUNDAY = 1;
	TextView title, scheduleTitle;
	GridView calendar;
	GridLayout weekOfDay;
	Calendar mThisMonthCalendar;
	LinearLayout linear = null;
	MyDBHelper mDBHelper;
	DAO dao;
	String currentDate;
	public TodayListAdapter tlAdapter;
		
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.d(TAG, "onCreateView() - month");
		View root = inflater.inflate(R.layout.monthdiary, container, false);

		ImageButton bPrevMonth = (ImageButton) root.findViewById(R.id.prev);
		ImageButton bNextMonth = (ImageButton) root.findViewById(R.id.next);
		//Button bPrevMonth = (Button) root.findViewById(R.id.prev);
		//Button bNextMonth = (Button) root.findViewById(R.id.next);
		
		title = (TextView) root.findViewById(R.id.title);
		calendar = (GridView) root.findViewById(R.id.calendar);
		weekOfDay = (GridLayout) root.findViewById(R.id.weekofmonthname);
		
		mDayList = new ArrayList<DayInfo>();

		mThisMonthCalendar = Calendar.getInstance();
		mThisMonthCalendar.set(Calendar.DAY_OF_MONTH, 1);
		getCalendar(mThisMonthCalendar);
		
		//다음달, 이전달 버튼
		bPrevMonth.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mThisMonthCalendar = getLastMonth(mThisMonthCalendar);
				getCalendar(mThisMonthCalendar);
			}
		});

		bNextMonth.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mThisMonthCalendar = getNextMonth(mThisMonthCalendar);
				getCalendar(mThisMonthCalendar);
			}
		});


		
		//날짜를 클릭했을때 등록
		calendar.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				SharedPreferences pref = getActivity().getSharedPreferences("date", 0);
				SharedPreferences.Editor edit = pref.edit();
				edit.putInt("year", mDayList.get(position).getYear());
				edit.putInt("month", mDayList.get(position).getMonth());
				edit.putInt("day", mDayList.get(position).getDay());
				edit.commit();
					
				linear = (LinearLayout) View.inflate(getActivity(), R.layout.todaylist, null);
				
				final int year = mDayList.get(position).getYear();
				final int month = mDayList.get(position).getMonth();
				final int day = mDayList.get(position).getDay();	
				final String stime = String.format("%4d년 %d월 %d일", year, month, day);
				currentDate = String.format("%4d/%d/%d", year, month, day);
				
				Log.d(TAG, currentDate);
				
				//select쿼리 결과. 해당날짜에 대한 스케쥴 목록 리스트
				dao = DAO.open(getActivity());
				arList = dao.selectTodayScheduleFromDate(currentDate);
							
				//날짜를 선택하면 다이얼로그에 linear를 전개.
				tlAdapter = new TodayListAdapter(getActivity(), arList, R.layout.todaylistlayout);
				ListView todayList = (ListView) linear.findViewById(R.id.todaylistview);
				todayList.setAdapter(tlAdapter);
				//tlAdapter.notifyDataSetChanged();
				
				//스케쥴일 있는날과 스케쥴이 없는날 ListView에 다르게 출력
				if(arList.size() == 0){
					new AlertDialog.Builder(getActivity())
					.setTitle(stime)
					.setMessage("등록된 일정이 없음")
					.setPositiveButton("일정을 추가하려면 여기 클릭!", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(getActivity(), Detail.class);						
							startActivity(intent);
						}
						
					}).show();
				} else {
					new AlertDialog.Builder(getActivity())
					.setTitle(stime)
					.setView(linear)
					.setPositiveButton("일정을 추가하려면 여기 클릭!", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(getActivity(), Detail.class);		
							startActivity(intent);
						}
						
					}).show();
				}
				 
				//스케쥴이 있는날짜의 다이얼로그 ListView에 출력된 스케쥴을 클릭시 해당 스케쥴이 나오는 Deatil.class로 이동
				todayList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> adapterView, View clickedView, int pos, long id) {
						Intent intent = new Intent(getActivity(), Detail.class);
		
						intent.putExtra("ParamTitle", arList.get(pos).getTitle());
						intent.putExtra("ParamStartDate", arList.get(pos).getStartDate());
						intent.putExtra("ParamStartTime", arList.get(pos).getStartTime());
						intent.putExtra("ParamAlarmInterval", arList.get(pos).getAlarmInterval());
						intent.putExtra("ParamMemo", arList.get(pos).getMemo());
						
						startActivity(intent);
					}
					
				});
				
			}
		});

		
		
		return root;
	}
		
	//캘린더 모양, 날짜 계산
	private void getCalendar(Calendar calendar) {
		int prevMonthStartDay;
		int dayOfMonth;
		int thisMonthLastDay;
		DayInfo day;
		
		mDayList.clear();

		// 이번달 시작일의 요일을 구한다. 시작일이 일요일인 경우 인덱스를 1(일요일)에서 8(다음주 일요일)로 바꾼다.
		dayOfMonth = calendar.get(Calendar.DAY_OF_WEEK);
		thisMonthLastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		calendar.add(Calendar.MONTH, -1);

		// 지난달의 마지막 일자를 구한다.
		prevMonthStartDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		calendar.add(Calendar.MONTH, 1);

		if (dayOfMonth == SUNDAY) {
			dayOfMonth += 7;
		}

		prevMonthStartDay -= (dayOfMonth - 1) - 1;

		//오늘의 날짜를 반환
		title.setText(mThisMonthCalendar.get(Calendar.YEAR) + "년 " + (mThisMonthCalendar.get(Calendar.MONTH) + 1) + "월");

		//
		for (int i = 0; i < dayOfMonth - 1; i++) {
			int date = prevMonthStartDay + i;
			day = new DayInfo();
			day.setDay(date);
			day.setInMonth(false);
			day.setMonth(mThisMonthCalendar.get(Calendar.MONTH));
			day.setYear(mThisMonthCalendar.get(Calendar.YEAR) - 1);
			mDayList.add(day);
		}

		for (int i = 1; i <= thisMonthLastDay; i++) {
			day = new DayInfo();
			day.setDay(i);
			day.setInMonth(true);
			day.setMonth(mThisMonthCalendar.get(Calendar.MONTH) + 1);
			day.setYear(mThisMonthCalendar.get(Calendar.YEAR));
			mDayList.add(day);
		}

		for (int i = 1; i < 42 - (thisMonthLastDay + dayOfMonth - 1) + 1; i++) {
			day = new DayInfo();
			day.setDay(i);
			day.setInMonth(false);
			day.setMonth(mThisMonthCalendar.get(Calendar.MONTH) + 2);
			day.setYear(mThisMonthCalendar.get(Calendar.YEAR) + 1);
			mDayList.add(day);
		}

		initCalendarAdapter();
	}

	//이전달 계산
	private Calendar getLastMonth(Calendar calendar) {
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
		calendar.add(Calendar.MONTH, -1);
		title.setText(mThisMonthCalendar.get(Calendar.YEAR) + "년 " + (mThisMonthCalendar.get(Calendar.MONTH) + 1) + "월");
		return calendar;
	}

	//다음달 계산
	private Calendar getNextMonth(Calendar calendar) {
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
		calendar.add(Calendar.MONTH, +1);
		title.setText(mThisMonthCalendar.get(Calendar.YEAR) + "년 " + (mThisMonthCalendar.get(Calendar.MONTH) + 1) + "월");
		return calendar;
	}

	//그리드뷰에 전개할 날짜들의 레이아웃
	private void initCalendarAdapter() {
		mCalendarAdapter = new MonthCalendarAdapter(getActivity(), R.layout.monthday, mDayList);
		calendar.setAdapter(mCalendarAdapter);

	}
		
	public class MonthCalendarAdapter extends BaseAdapter {
		private ArrayList<DayInfo> dayList;
		ArrayList<MyItem> dayNameList;
		private Context context;
		private int resource;
		private LayoutInflater inflater;

		public MonthCalendarAdapter(Context context, int textResource, ArrayList<DayInfo> dayList) {
			this.context = context;
			this.dayList = dayList;
			this.resource = textResource;
			this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			dao = DAO.open(context);
		}

		public int getCount() {
			return dayList.size();
		}

		public Object getItem(int position) {
			return dayList.get(position);
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			DayInfo day = dayList.get(position);
			DayViewHolde dayViewHolder;
			
			if (convertView == null) {
				convertView = inflater.inflate(resource, null);

				if (position % 7 == 6) {
					convertView.setLayoutParams(new GridView.LayoutParams(getCellWidthDP() + getRestCellWidthDP(), getCellHeightDP()));
				} else {
					convertView.setLayoutParams(new GridView.LayoutParams(getCellWidthDP(), getCellHeightDP()));
				}

				dayViewHolder = new DayViewHolde();
				dayViewHolder.background = (LinearLayout) convertView.findViewById(R.id.day_background);
				dayViewHolder.tvDay = (TextView) convertView.findViewById(R.id.day);
				dayViewHolder.tvPen = (ImageView) convertView.findViewById(R.id.schedulepen);
				dayViewHolder.tvPen.setVisibility(View.INVISIBLE);
				
				convertView.setTag(dayViewHolder);

			} else {
				dayViewHolder = (DayViewHolde) convertView.getTag();
			}

			if (day != null) {
				dayViewHolder.tvDay.setText(String.valueOf(day.getDay()));

				if (day.isInMonth()) {
					if (position % 7 == 0) {
						dayViewHolder.tvDay.setTextColor(Color.RED);
					} else if (position % 7 == 6) {
						dayViewHolder.tvDay.setTextColor(Color.BLUE);
					} else {
						dayViewHolder.tvDay.setTextColor(Color.BLACK);
					}
				} else {
					dayViewHolder.tvDay.setTextColor(Color.GRAY);
				}
			}
							
			
			/*dayNameList = dao.selectTotalSchedule();
			
			if(dayNameList.size() != 0){
				dayViewHolder.tvPen.setVisibility(View.VISIBLE);
			} else {
				dayViewHolder.tvPen.setVisibility(View.INVISIBLE);
			}*/
			
			return convertView;
		}

		public class DayViewHolde {
			public LinearLayout background;
			public TextView tvDay;
			public ImageView tvPen;
		}

		private int getCellWidthDP() {
			int width = context.getResources().getDisplayMetrics().widthPixels;
			int cellWidth = width / 7;

			return cellWidth;
		}

		private int getRestCellWidthDP() {
			int width = context.getResources().getDisplayMetrics().widthPixels;
			int cellWidth = width % 7;

			return cellWidth;
		}

		private int getCellHeightDP() {
			int height = context.getResources().getDisplayMetrics().widthPixels;
			int cellHeight = height / 6;

			return cellHeight;
		}
			
	}
		
	//날짜를 클릭했을때, 스케쥴이 있을시 ListView에 붙일 해당 스케쥴 어댑터
	public class TodayListAdapter extends BaseAdapter {
		Context context;
		LayoutInflater inflate;
		int layout;
		ArrayList<MyItem> tList;	//해당정보 DB에서 select해와야함. DAO에서 처리. 타이틀을 select해서 setText함
		
		public TodayListAdapter(Context context, ArrayList<MyItem> tList, int layout) {
			this.context = context;
			this.tList =  tList;
			this.inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.layout = layout;
			dao = DAO.open(context);
		}
		
		@Override
		public int getCount() {
			return tList.size();
		}

		@Override
		public Object getItem(int position) {
			return tList.get(position).getTitle();
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int pos = position;
			if(convertView == null){
				convertView = inflate.inflate(layout, parent, false);
			}
			
			TextView titleSec = (TextView) convertView.findViewById(R.id.todaylisttitle);
			titleSec.setText(tList.get(position).getTitle());
						
			return convertView;
		}

	}
}
